// pages/school_detail/school_detail.js
const app = getApp();
import { u_formatTimestamp } from '../../config/tool.js';
import { sdetail, scartDel, scartEdit } from '../../config/https.js';
var WxParse = require('../../wxParse/wxParse.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    needLoad: true, // 需要加载
    cindex: 0,
    id: '', // 商品id
    goodsType: 0, //商品类型 0正常商品 1两人团商品 2秒杀 3砍价
    isStandard: false,//保障信息弹框
    isParams: false,// 产品参数弹框
    showNumsAdd: false, // 显示单规格弹窗
    isOptions: false, // 显示多规格弹窗
    goodsInfo: '', // 商品数据
    specInfo: '', // 规格信息
    specList: '', // 规格列表
    selectSpecId: '', // 选中规格id
    buyNum: 1, // 购买数量
    chooseType: 0, // 1加入购物车 2立即购买 3选择规格按钮
    specName: '', // 规格名称
    buyList: [], // 已购买用户列表
    showShare: false, // 是否显示分享弹窗
    userImg: '', // 用户头像信息
    posterUrl: '', // 生成的海报
    showCart: false, // 是否展示购物车弹窗
    scartInfo: '', // 详情购物车信息
    once: true, // 防止重复提交
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      schoolId: options.school
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取购物车数量
    this.setData({
      cart_nums: Number(wx.getStorageSync('cart_nums'))
    })
    if (app.globalData.userId) {
      this.getCarts();
    }

    if (this.data.needLoad) {
      let that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            wH: res.screenWidth / 750
          })
        },
      })
      if (wx.getStorageSync('userInfos')) {
        wx.getImageInfo({
          src: JSON.parse(wx.getStorageSync('userInfos')).avatar,
          success(data) {
            that.setData({
              userImg: data.path,
            })
          }
        })
      }
      this.initData();
      this.getData();
    }
  },

  // 获取数据
  getData() {
    app.loading();
    let that = this;
    wx.request({
      url: app.baseURL + 'item/getItemDetail',
      data: {
        goods_id: this.data.id,
        token: app.globalData.userId ? app.globalData.userId : '',
        school_id: this.data.schoolId
      },
      success(data) {
        let res = data.data;
        wx.hideLoading();
        if (res.code == 1) {
          let info = res.data.content;
          WxParse.wxParse('detailinfo', 'html', info, that, 5);

          res.data.ShopingCart.list.forEach((item) => {
            if (item.goods_id == that.data.id) {
              that.setData({
                scartInfo: item
              })
            }
          })

          if (res.data.comment) {
            res.data.comment.add_time = u_formatTimestamp(res.data.comment.add_time * 1000, 'ymd')
          }

          that.setData({
            goodsInfo: res.data,
            goodsType: res.data.is_marketing,
            buyList: res.data.buyList,
            cartData: res.data.ShopingCart
          })
          that.getImgData();
        } else {
          app.$tip(res.msg);
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/home/home',
            })
          }, 1500)
        }
      }
    })
  },

  // 获取购物车数量
  getCarts(cb) {
    let that = this;
    sdetail({
      goods_id: this.data.id,
      token: app.globalData.userId ? app.globalData.userId : '',
      school_id: this.data.schoolId
    }).then(res => {
      if (res.code == 1) {
        res.data.ShopingCart.list.forEach((item) =>{
          if (item.goods_id == this.data.id) {
            this.setData({
              scartInfo: item
            })
          }
        })
        that.setData({
          goodsInfo: res.data,
          goodsType: res.data.is_marketing,
          buyList: res.data.buyList,
          cartData: res.data.ShopingCart
        })

        typeof cb == 'function' && cb();
      }else{
        app.$tip(res.msg);
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/home/home',
          })
        }, 1500)
      }
    })
  },

  getImgData() {
    let that = this;
    wx.getImageInfo({
      src: that.data.goodsInfo.spec_image,
      success(data) {
        that.setData({
          spec_image: data.path,
        })
      }
    })
    wx.getImageInfo({
      src: that.data.goodsInfo.QRcode,
      success(data) {
        that.setData({
          qrcode: data.path,
        })
      }
    })
  },

  // 格式化数据
  initData() {
    this.setData({
      needLoad: true, // 需要加载
      cindex: 0,
      goodsType: 0, //商品类型 0正常商品 1两人团商品 2秒杀 3砍价
      isStandard: false,//保障信息弹框
      isParams: false,// 产品参数弹框
      isOptions: false, // 显示多规格弹窗
      showNumsAdd: false, // 显示单规格弹窗
      goodsInfo: '', // 商品数据
      specInfo: '', // 规格信息
      specList: [], // 规格列表
      selectSpecId: '', // 选中规格id
      buyNum: 1, // 购买数量
      chooseType: 0,
      specName: '', // 规格名称
      showShare: false, // 是否展示分享弹窗
      userImg: '', // 用户头像信息
      posterUrl: '', // 生成的海报
      showCart: false, // 是否展示购物车弹窗
      scartInfo: '', // 详情购物车信息
      once: true, // 防止重复提交
    })
  },

  // 展示服务
  showService() {
    this.setData({
      isStandard: !this.data.isStandard
    })
  },

  // 展示参数
  showDetails() {
    this.setData({
      isParams: !this.data.isParams
    })
  },

  // 显示规格弹窗
  // 根据type值不同切换 1加入购物车 2立即购买 3选择规格按钮
  // 根据this.data.goodsInfo.spec_type值不同判断规格 10单规格 20多规格
  showSpec(e) {
    // 未登录
    if (!app.globalData.userId) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录,请先登录!',
        confirmText: '去登录',
        confirmColor: '#57b127',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/wxLogin/wxLogin',
            })
          } else if (res.cancel) {

          }
        }
      })
      return
    }

    // 判断上下架状态
    if (this.data.goodsInfo.goods_status == 20) {
      app.$tip('该商品已下架！');
      return
    }

    // 判断也没有限制购买 1没有 2限制
    if (this.data.goodsInfo.is_limit_buy == 2) {
      app.$tip('购买数量受限，不能购买!');
      return
    }

    // 判断是否库存充足
    if (Number(this.data.goodsInfo.stock_num) < 1) {
      app.$tip('商品库存不足!');
      return
    }

    let type = e.currentTarget.dataset.type, that = this;
    this.setData({
      chooseType: type,
    })
    // 单规格
    if (this.data.goodsInfo.spec_type == 10) {
      // 加入购物车
      if (type == 1) {
        app.loading();
        wx.request({
          url: app.baseURL + 'item/addShopingCart',
          data: {
            goods_id: that.data.id,
            num: 1,
            goods_spec_id: that.data.goodsInfo.goods_spec_id,
            type: 1, // 1正常商品 2秒杀 3特价
            token: app.globalData.userId,
            school_id: this.data.schoolId
          },
          success(suc) {
            if (suc.data.code == 1) {
              wx.request({
                url: app.baseURL + 'item/getItemDetail',
                data: {
                  goods_id: that.data.id,
                  token: app.globalData.userId ? app.globalData.userId : '',
                  school_id: that.data.schoolId
                },
                success(data) {
                  let res = data.data;
                  wx.hideLoading();
                  if (res.code == 1) {
                    app.$tip('加入购物车成功!');
                    that.setData({
                      goodsInfo: res.data,
                      cartData: res.data.ShopingCart
                    })
                  }
                }
              })
              // setTimeout(() => {
              // that.initData();
              // that.getData();
              // }, 1500)
            } else {
              app.$tip(suc.data.msg);
            }
          }
        })
      }
      // 立即购买
      // 判断库存
      if (type == 2) {
        that.setData({
          showNumsAdd: true
        })
      }

    }
    // 多规格 请求规格数据 展示规格选择弹窗
    if (this.data.goodsInfo.spec_type == 20) {
      app.loading();
      wx.request({
        url: app.baseURL + 'item/getGoodsSpec',
        data: {
          goods_id: that.data.id,
          school_id: that.data.schoolId
        },
        success(data) {
          let res = data.data;
          wx.hideLoading();
          if (res.code == 1) {
            let arr = [];
            res.data.info.item_sku.forEach((item) => {
              // item.specId = '';
              item.specId = item.sub[0].id;
              arr.push(item.sub[0].id);
            })
            that.setData({
              // specInfo: res.data.info,
              specList: res.data.info.item_sku,
              isOptions: true
            })
            that.getSpecInfo(arr.join('_'))
          } else {
            app.$tip(res.msg);
          }
        }
      })
    }
  },

  // 选择规格
  choose(e) {
    let arr = [];
    // 父集下标
    let findex = e.currentTarget.dataset.findex;
    let old = this.data.specList;
    // 改变当前规格选中的规格id
    old[findex].specId = e.currentTarget.dataset.id;
    this.setData({
      specList: old
    })
    this.data.specList.forEach((item) => {
      if (item.specId) {
        arr.push(item.specId)
      }
    })
    this.getSpecInfo(arr.join('_'))
  },

  // 获取选中的规格的信息
  getSpecInfo(id) {
    let that = this;
    wx.request({
      url: app.baseURL + 'item/getItemSku',
      data: {
        goods_id: that.data.id,
        sku_id: id,
        school_id: that.data.schoolId
      },
      success(data) {
        let res = data.data;
        if (res.code == 1) {
          that.setData({
            specInfo: res.data,
            selectSpecId: res.data.goods_spec_id
          })
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },

  // 数量变化
  // 多规格
  // 加
  addNums() {
    // 判断库存
    if (Number(this.data.buyNum) < Number(this.data.specInfo.stock_num)) {
      this.setData({
        buyNum: Number(this.data.buyNum) + 1
      })
    } else {
      app.$tip('不能大于库存!');
    }
  },
  // 减
  cutNums() {
    if (Number(this.data.buyNum) > 1) {
      this.setData({
        buyNum: Number(this.data.buyNum) - 1
      })
    } else {
      app.$tip('最少购买一件!');
    }
  },

  // 单规格
  addNumber() {
    // 判断库存
    if (Number(this.data.buyNum) < Number(this.data.goodsInfo.stock_num)) {
      this.setData({
        buyNum: Number(this.data.buyNum) + 1
      })
    } else {
      app.$tip('不能大于库存!');
    }
  },

  // 去确认订单页
  toPlaceorder() {
    let that = this;
    if (this.data.goodsInfo.spec_type == 20 && !this.data.selectSpecId) {
      app.$tip('请选择规格!');
      return
    }
    // 加入购物车
    if (this.data.chooseType == 1) {
      app.loading();
      wx.request({
        url: app.baseURL + 'item/addShopingCart',
        data: {
          goods_id: that.data.id,
          num: that.data.buyNum,
          goods_spec_id: that.data.selectSpecId,
          type: 1, // 1正常商品 2秒杀 3特价
          token: app.globalData.userId,
          school_id: that.data.schoolId
        },
        success(suc) {
          if (suc.data.code == 1) {
            that.setData({
              isOptions: false,
              showNumsAdd: false,
            })
            wx.request({
              url: app.baseURL + 'item/getItemDetail',
              data: {
                goods_id: that.data.id,
                token: app.globalData.userId ? app.globalData.userId : '',
                school_id: that.data.schoolId
              },
              success(data) {
                let res = data.data;
                wx.hideLoading();
                if (res.code == 1) {
                  app.$tip('加入购物车成功!');
                  that.setData({
                    goodsInfo: res.data,
                    cartData: res.data.ShopingCart
                  })
                }
              }
            })
            // setTimeout(() => {
            // that.initData();
            // that.getData();
            // }, 1500)
          } else {
            app.$tip(suc.data.msg);
          }
        }
      })
    };
    // 立即购买
    if (this.data.chooseType == 2) {
      let paramsInfo = {
        goods_id: this.data.id,
        goods_spec_id: that.data.goodsInfo.spec_type == 20 ? this.data.selectSpecId : that.data.goodsInfo.goods_spec_id,
        num: this.data.buyNum,
        type: 1, // 1正常商品 2限时抢购 4两人团购 5团购单独1购买
        is_status: 1, // 1配送商品 2自提商品
        marketing_id: that.data.goodsInfo.marketing_id, // 活动id
        // is_status: that.data.goodsInfo.
      }
      wx.navigateTo({
        url: '/pages/confirm_order/confirm_order?data=' + JSON.stringify(paramsInfo) + '&from=detail&sendType=' + this.data.goodsInfo.delivery_methods,
      })
    };
    // 选择规格按钮
    if (this.data.chooseType == 3) {
      this.setData({
        isOptions: false,
        specName: this.data.specInfo.key_name
      })
    };
  },

  // 关闭弹窗
  closeBuy() {
    this.setData({
      isOptions: false,
      showNumsAdd: false
    })
  },

  // 去首页
  toIndex() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  // 收藏
  collectBtn() {
    // 未登陆
    if (!app.globalData.userId) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录,请先登录!',
        confirmText: '去登录',
        confirmColor: '#57b127',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/wxLogin/wxLogin',
            })
          } else if (res.cancel) {

          }
        }
      })
      return
    }

    let that = this;
    app.loading();
    if (that.data.goodsInfo.is_collect == 0) {
      wx.request({
        url: app.baseURL + 'Collection/addCollect?goods_id=' + that.data.id + '&token=' + app.globalData.userId,
        // data: {
        //   goods_id: that.data.id,
        //   token: app.globalData.userId,
        // },
        success(data) {
          let res = data.data;
          if (res.code == 1) {
            app.$tip(res.msg);
            setTimeout(() => {
              that.initData();
              that.getData();
            }, 1500)
          } else {
            app.$tip(res.msg);
          }
        }
      })
    } else {
      wx.request({
        url: app.baseURL + 'Collection/delCollect',
        data: {
          goods_id: that.data.id,
          token: app.globalData.userId,
        },
        success(data) {
          let res = data.data;
          if (res.code == 1) {
            app.$tip(res.msg);
            setTimeout(() => {
              that.initData();
              that.getData();
            }, 1500)
          } else {
            app.$tip(res.msg);
          }
        }
      })
    }
  },

  // 去购物车
  toCart() {
    wx.switchTab({
      url: '/pages/car/car',
    })
  },

  // 查看全部评价
  toEvaluate() {
    wx.navigateTo({
      url: '/pages/comment/comment?id=' + this.data.id,
    })
  },

  // 查看大图
  showBig(e) {
    this.setData({
      needLoad: false
    })
    let index = e.currentTarget.dataset.index;
    wx.previewImage({
      urls: this.data.goodsInfo.comment.images,
      current: this.data.goodsInfo.comment.images[index]
    })
  },

  // 展示分享弹窗
  showChoose() {
    // 未登陆
    if (!app.globalData.userId) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录,请先登录!',
        confirmText: '去登录',
        confirmColor: '#57b127',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/wxLogin/wxLogin',
            })
          } else if (res.cancel) {

          }
        }
      })
      return
    }

    this.setData({
      showShare: !this.data.showShare
    })
  },

  /**
  * 多行文字处理，每行显示数量
  * @param text 为传入的文本
  * @param num  为单行显示的字节长度
  */
  textByteLength(text, num) {
    //console.log(text,num) 
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  // 制作海报
  makePoster() {
    if (this.data.posterUrl) {
      let arr = [];
      arr.push(this.data.posterUrl);
      wx.previewImage({
        urls: arr,
      })
    } else {
      let that = this;
      //获取当前屏幕的宽度
      var rpx = wx.getSystemInfoSync().windowWidth / 375;
      let ctx = wx.createCanvasContext('myCanvas');
      const CONTENT_ROW_LENGTH = 28; // 正文 单行显示字符长度
      let [contentLeng, contentArray, contentRows] = that.textByteLength(that.data.goodsInfo.goods_name, CONTENT_ROW_LENGTH);
      let contentH = 22 * 1;  //相当于行高  就是一行所占的高度
      let i = contentArray.length; //字体变成了几行？

      // 设置头部图片
      ctx.drawImage('/assets/img/share_logo.jpg', 0, 0, (270), (80))
      // 设置商品图片
      ctx.drawImage(that.data.spec_image, 0, (80), (270), (270))
      ctx.setFillStyle('white');
      ctx.fillRect(0, (350), (270), (80));

      // 设置价格
      ctx.rect(10, (290), (80), 20)
      ctx.setFillStyle('#e10b2b')
      ctx.fill()
      ctx.setFillStyle('#fff')//字体颜色
      ctx.setFontSize(10)//字体大小
      ctx.fillText('￥', (16), (306))
      ctx.setFillStyle('#fff')//字体颜色
      ctx.setFontSize(16)//字体大小
      ctx.fillText(that.data.goodsInfo.goods_price, (26), (306))

      // 设置小程序码
      ctx.drawImage(that.data.qrcode, (190), (356), (66), (66))

      ctx.setFillStyle('#333')//字体颜色
      ctx.setFontSize(12)//字体大小

      ctx.setTextAlign('left');//文字的对齐方式 左对齐
      var contentHh = 16;  //相当于行高  就是一行所占的高度
      var j = contentArray.length;

      for (let i = 0; i < contentArray.length; i++) {
        //第一个参数：在画布上输出的文本； 第二个参数：图像距离画布的左 x 坐标    第三个参数：图像距离画布的上角 y 坐标 
        ctx.fillText(contentArray[i], 10, (376 + contentHh * i));
      }
      // let that = this;
      // let ctx = wx.createCanvasContext('myCanvas');
      // // 设置头部图片
      // ctx.drawImage('/assets/img/share_logo.jpg', 0, 0, 270, 80)
      // // 设置商品图片
      // ctx.drawImage(that.data.spec_image, 0, 80, 270, 270)
      // ctx.setFillStyle('white');
      // ctx.fillRect(0, 350, 270, 80);
      // // 设置用户头像
      // ctx.drawImage(that.data.userImg, 196, 357, 66, 66)
      // // 设置小程序码
      // ctx.drawImage(that.data.qrcode, 8, 357, 66, 66)
      // // 设置扫码提示图片
      // ctx.drawImage('/assets/img/easyBuy.png', 80, 407, 110, 15)
      // ctx.setTextAlign('left')//设置文字要垂直居中

      // ctx.setFillStyle('#333')//字体颜色
      // ctx.setFontSize(10)//字体大小
      // ctx.fillText(that.data.goodsInfo.nickname, 80, 372)
      // ctx.fillText("华为全屋定制,共享购物时光", 80, 392)
      ctx.draw()
      //将画布转化成图片
      let timmm = setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: "myCanvas",
          fileType: 'jpg',
          success(daa) {
            wx.hideLoading();
            let arr = [];
            arr.push(daa.tempFilePath);
            wx.previewImage({
              urls: arr,
            })
            that.setData({
              posterUrl: daa.tempFilePath,
              needLoad: false,
              showShare: false
            })
            clearTimeout(timmm)
            wx.hideLoading()
          },
          fail(err) {
            wx.hideLoading();
            wx.showToast({
              title: '生成错误，请重试！',
              icon: 'none'
            })
            console.log(err)
          }
        })
      }, 600)
    }
  },

  // 购物车弹窗 显示隐藏
  closePopup() {
    if (this.data.cartData.total_num < 1) {
      return
    }
    this.setData({
      showCart: !this.data.showCart
    })
  },

  // 清空购物车
  clearCart(e) {
    let that = this, ids = e.currentTarget.dataset.ids;
    wx.showModal({
      title: '温馨提示',
      content: '您确定要清空购物车吗?',
      confirmText: '清空',
      confirmColor: '#57B127',
      success(suc) {
        if (suc.confirm) {
          scartDel({
            token: app.globalData.userId,
            ids: ids
          }).then(res => {
            if (res.code == 1) {
              that.getCarts();
              that.setData({
                showCart: false
              })
            } else {
              app.$tip(res.msg)
            }
          })
        } else if (suc.cancel) {
        }
      }
    })
  },

  // 阻止事件冒泡
  nothing() {
  },

  // 购物车数量变化
  // 减
  cartCut(e) {
    let that = this, index = e.currentTarget.dataset.index;
    if (!this.data.once) {
      return
    }
    this.setData({
      once: false
    })
    if (this.data.scartInfo.num == 1) {
      scartDel({
        token: app.globalData.userId,
        ids: this.data.scartInfo.id
      }).then(res => {
        that.setData({
          once: true
        })
        if (res.code == 1) {
          that.getCarts(() => {
            if (that.data.cartData.total_num < 1) {
              that.setData({
                showCart: false,
              })
            }
          });
        } else {
          app.$tip(res.msg)
        }
      })
    } else {
      scartEdit({
        token: app.globalData.userId,
        id: this.data.scartInfo.id,
        num: 1,
        type: 2, // 1加 2减
      }).then(res => {
        that.setData({
          once: true
        })
        if (res.code == 1) {
          that.getCarts();
        } else {
          app.$tip(res.msg)
        }
      })
    }
  },

  // 加
  cartAdd(e) {
    let that = this, index = e.currentTarget.dataset.index;
    if (!this.data.once) {
      return
    }
    this.setData({
      once: false
    })
    scartEdit({
      token: app.globalData.userId,
      id: this.data.scartInfo.id,
      num: 1,
      type: 1, // 1加 2减
    }).then(res => {
      that.setData({
        once: true
      })
      if (res.code == 1) {
        that.getCarts();
      } else {
        app.$tip(res.msg)
      }
    })
  },

  // 结算
  toBuy(){
    if (!this.data.cartData.shoping_cart_ids) {
      app.$tip('请先选择商品!');
      return
    }
    let data = {
      ids: this.data.cartData.shoping_cart_ids,
      type: 1,
      school_id: this.data.schoolId
    }
    wx.navigateTo({
      url: '/pages/confirm_order/confirm_order?data=' + JSON.stringify(data) + '&from=cart',
    })
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onHide: function () {
    this.setData({
      needLoad: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: this.data.goodsInfo.goods_name,
        imageUrl: this.data.goodsInfo.images,
        path: '/pages/school_detail/school_detail?id=' + this.data.id
      }
    }
    return {
      title: this.data.goodsInfo.goods_name,
      imageUrl: this.data.goodsInfo.images,
      path: '/pages/school_detail/school_detail?id=' + this.data.id
    }
  }
})